package com.adams.dcxt.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.adams.dcxt.bean.Dishes;
import com.adams.dcxt.bean.Order;
import com.adams.dcxt.bean.OrderDishes;
import com.adams.dcxt.core.Contants;
import com.adams.dcxt.core.DateUtils;
import com.adams.dcxt.core.DishesTemp;
import com.adams.dcxt.core.Page;
import com.adams.dcxt.core.TableMaps;
import com.adams.dcxt.facade.OrderFacade;
import com.adams.dcxt.service.DishesService;

/**
 * 我的菜单
 * 
 * @author 904912
 * 
 */
public class OrderAction extends BaseAction {

	private static final long serialVersionUID = -6833993806220247910L;
	private String tableId; // 餐桌号
	private static Logger logger = LoggerFactory.getLogger(OrderAction.class);
	private OrderFacade orderFacade;
	private String dids; // 菜单ID,用逗号分隔
	private String uid; // 服务员工号
	private DishesService dishesService;
	private String dname;// 菜单名
	private String price;// 价格
	private String count;// 份数
	private String did;// 菜单主键

	public String removeATmpOrder() {
		// 根据菜单主键找出菜单 份数减一 份数为1 删除
		Set<DishesTemp> set = TableMaps.getInstance()
				.getTempsByTableId(tableId);
		Map response = new HashMap();
		if (StringUtils.isBlank(did) || StringUtils.isBlank(tableId)) {
			response.put("data", "删除失败");
			response.put("success", false);
			write(JSONObject.fromObject(response).toString());
			return null;
		}
		if (set != null) {
			for (DishesTemp temp : set) {
				if (temp.getDishesId().toString().equals(did)) {
					synchronized (temp) {
						if ("1".equals(temp.getCount())) {
							// 移除此对象
							set.remove(temp);
						} else {
							// 减一
							String count = temp.getCount();
							int newcount = Integer.parseInt(count) - 1;
							temp.setCount(String.valueOf(newcount));
						}
					}
				}
			}
		}
		response.put("data", "删除成功");
		response.put("success", true);
		write(JSONObject.fromObject(response).toString());
		return null;
	}

	/**
	 * 存储临时选择菜单
	 * 
	 * @return
	 */
	public String saveTmpOrder() {
		DishesTemp temp = new DishesTemp();
		temp.setName(dname);
		Map response = new HashMap();
		if (StringUtils.isBlank(did) || StringUtils.isBlank(tableId)) {
			response.put("data", "选择菜单失败");
			response.put("success", false);
			write(JSONObject.fromObject(response).toString());
			return null;
		} else {
			temp.setDishesId(Long.parseLong(did));
		}
		temp.setPrice(price);
		temp.setCount(count);
		TableMaps.getInstance().setTemp(tableId, temp);
		response.put("data", "选择菜单成功");
		response.put("success", true);
		write(JSONObject.fromObject(response).toString());
		return null;
	}

	public String getTmpOrder() {
		Set<DishesTemp> set = TableMaps.getInstance()
				.getTempsByTableId(tableId);
		Map response = new HashMap();
		response.put("data", set);
		response.put("success", true);
		write(JSONObject.fromObject(response).toString());
		return null;
	}

	public String order() {
		Map response = new HashMap();
		try {
			if (StringUtils.isNotBlank(dids) && StringUtils.isNotBlank(uid)
					&& StringUtils.isNotBlank(tableId)) {
				int totalMoney = 0;
				String dishesIds[] = dids.split(",");
				List<OrderDishes> oDishesList = new ArrayList<OrderDishes>();
				StringBuilder str = new StringBuilder();
				for (String idStr : dishesIds) {
					Dishes d = dishesService.get(Long.parseLong(idStr));
					if (d != null) {
						int price = d.getDishesPrice();
						float rate = Float.parseFloat(d.getSpecialRate());
						double finalPriceDouble = price * rate;
						BigDecimal bd = new BigDecimal(finalPriceDouble);
						int finalPrice = bd.setScale(0,
								BigDecimal.ROUND_HALF_UP).intValue();
						totalMoney += finalPrice;
						OrderDishes od = new OrderDishes();
						od.setDishes(d);
						oDishesList.add(od);
						str.append(d.getDishesId()).append(",");
					}
				}
				String ids = "";
				if (str.length() > 0)
					ids = str.substring(0, str.length() - 1);
				Order order = new Order();
				order.setOrderTime(DateUtils.getNowTime("yyyy-MM-dd HH:mm:ss"));
				order.setTable(tableId);
				order.setTotalMoney(totalMoney);
				order.setStatus(Contants.ORDER_NO_CHECK);
				order.setWaiterId(Long.parseLong(uid));
				orderFacade.placeOrder(order, oDishesList);
				TableMaps.getInstance().clearItem(tableId, ids);
				response.put("data", "下单成功");
				response.put("success", true);
			} else {
				response.put("data", "下单失败");
				response.put("success", false);

			}
		} catch (Exception e) {
			response.put("data", "下单失败");
			response.put("success", false);
			logger.error("下单失败原因：", e);
		}
		write(JSONObject.fromObject(response).toString());
		return null;

	}

	public String getOrderByTable() {
		Map response = new HashMap();
		Page<OrderDishes> page = new Page<OrderDishes>();
		setPage(page);
		try {
			page = orderFacade.getOrderDishes(tableId, page);
		} catch (Exception e) {
			logger.error("查询我的菜单错误:", e);
			response.put("data", "");
			response.put("success", false);
			write(JSONObject.fromObject(response).toString());
			return null;
		}
		Integer totalPage = page.getTotalPage();
		List<OrderDishes> list = page.getResultList();
		response.put("data", list);
		response.put("success", true);
		response.put("totalPage", totalPage);
		write(JSONObject.fromObject(response).toString());
		return null;
	}

	public String getTableId() {
		return tableId;
	}

	public void setTableId(String tableId) {
		this.tableId = tableId;
	}

	public OrderFacade getOrderFacade() {
		return orderFacade;
	}

	public void setOrderFacade(OrderFacade orderFacade) {
		this.orderFacade = orderFacade;
	}

	public String getDids() {
		return dids;
	}

	public void setDids(String dids) {
		this.dids = dids;
	}

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public DishesService getDishesService() {
		return dishesService;
	}

	public void setDishesService(DishesService dishesService) {
		this.dishesService = dishesService;
	}

	public String getDname() {
		return dname;
	}

	public void setDname(String dname) {
		this.dname = dname;
	}

	public String getPrice() {
		return price;
	}

	public void setPrice(String price) {
		this.price = price;
	}

	public String getCount() {
		return count;
	}

	public void setCount(String count) {
		this.count = count;
	}

	public String getDid() {
		return did;
	}

	public void setDid(String did) {
		this.did = did;
	}

}
